package com.sad.jetpack.v1.datamodel.demo;

import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.sad.jetpack.v1.datamodel.api.IDataModelResponse;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.ErrorMessage;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatSessionManager;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatTextSessionListener;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCMember;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatHeader;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCChatIntent;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCNewChatErrorMessageListener;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCServerAddress;
import com.sad.jetpack.v1.datamodel.api.extension.client.socket.ipc.IPCTerminal;
import com.sad.jetpack.v1.datamodel.api.utils.LogcatUtils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class SecondActivity extends AppCompatActivity {
    private TextView tv_console;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
        initView();
        testClientSocket("4","0001","ETO-伊文斯");
        testClientSocket("6","0002","ETO-潘寒");
    }
    private void initView(){
        tv_console=findViewById(R.id.console2);
        findViewById(R.id.sendMsg1).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               if (sessionManager1 !=null){
                   new Thread(new Runnable() {
                       @Override
                       public void run() {
                           try {
                               sessionManager1.getChatMessenger().syncSend("我是三体文明1号发射台，ETO何在？".getBytes(StandardCharsets.UTF_8),1024,false);
                           } catch (Exception e) {
                               e.printStackTrace();
                           }
                       }
                   }).start();
               }
            }
        });

        findViewById(R.id.sendMsg2).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (sessionManager1 !=null){
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                sessionManager2.getChatMessenger().syncSend("我是三体文明2号发射台，ETO何在？".getBytes(StandardCharsets.UTF_8),1024,false);
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }
            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (sessionManager1 !=null){
                        sessionManager1.getSocket().close();
                    }
                    if (sessionManager2!=null){
                        sessionManager1.getSocket().close();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }).start();

    }

    private void testClientSocket(String fromCid,String toCid,String toAlias){
        IPCChatHeader header=createTestHeader(toCid,toAlias);
        testCreateIPCChat(header,fromCid);
    }

    IPCChatSessionManager sessionManager1;
    IPCChatSessionManager sessionManager2;
    private void testCreateIPCChat(IPCChatHeader header,String cid){
        IPCMember ipcMember=IPCMember.newInstance()
                .setAlias("三体文明信号发射塔")
                .setClientId(cid)
                .setDescription("探测新的家园")
                ;
        header.setFrom(ipcMember);
        try {
            IPCTerminal.connect(IPCServerAddress.getServerAddress(getApplicationContext(),"xcn105330").getIp(), 10821, header, new IPCChatTextSessionListener() {
                        @Override
                        public void onReadyToStart(IPCChatSessionManager sessionManager) {
                            if (Integer.valueOf(cid)>5){
                                sessionManager1=sessionManager;
                            }
                            else {
                                sessionManager2=sessionManager;
                            }
                            LogcatUtils.e("IPC测试-------------->客户端生成会话管理器："+sessionManager);
                        }

                        @Override
                        public void onChatText(IPCChatSessionManager sessionManager, ITextReader reader, String s) throws Exception {
                            LogcatUtils.e("IPC测试-------------->客户端接收到监听端的回复信息："+s);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    tv_console.append(s+"\n");
                                }
                            });
                        }
                    }, new IPCNewChatErrorMessageListener() {
                        @Override
                        public void onReceivedErrorMessage(IPCMember selfMember, ErrorMessage errorMessage) {

                        }
                    });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private IPCChatHeader createTestHeader(String toCid,String toAlias){
        IPCChatHeader header=new IPCChatHeader();
        IPCChatIntent intent=new IPCChatIntent();
        intent.setParams("探测信号");
        header.setIntent(intent);
        header.setId("xxx");
        header.setToAll(false);
        List<IPCMember> to=new ArrayList<>();
        IPCMember toMember=IPCMember.newInstance();
        toMember.setClientId(toCid)
                .setAlias(toAlias);
        to.add(toMember);
        header.setTo(to);
        return  header;
    }

}